using System;
using System.Drawing;
using System.Windows.Forms;

namespace DevelopersToolbox {
    public partial class NumberedTextBoxUC : UserControl {

        public NumberedTextBoxUC() {
            InitializeComponent();
            _numberLabel.Font = new Font(_richTextBox.Font.FontFamily, _richTextBox.Font.Size + 1.019f);
        }


        private void updateNumberLabel() {
            //we get index of first visible char and number of first visible line
            Point pos = new Point(0, 0);
            int firstIndex = _richTextBox.GetCharIndexFromPosition(pos);
            int firstLine = _richTextBox.GetLineFromCharIndex(firstIndex);

            //now we get index of last visible char and number of last visible line
            pos.X = ClientRectangle.Width;
            pos.Y = ClientRectangle.Height;
            int lastIndex = _richTextBox.GetCharIndexFromPosition(pos);
            int lastLine = _richTextBox.GetLineFromCharIndex(lastIndex);

            //this is point position of last visible char, we'll use its Y value for calculating numberLabel size
            pos = _richTextBox.GetPositionFromCharIndex(lastIndex);


            //finally, renumber label
            _numberLabel.Text = "";
            for (int i = firstLine; i <= lastLine + 1; i++) {
                _numberLabel.Text += i + 1 + "\n";
            }
        }

        public override string Text {
            get { return _richTextBox.Text; }
            set { _richTextBox.Text = value; }
        }

        public RichTextBox RichTextBox {
            get { return _richTextBox; }
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e) {
            updateNumberLabel();
        }

        private void richTextBox1_VScroll(object sender, EventArgs e) {
            //move location of numberLabel for amount of pixels caused by scrollbar
            int d = _richTextBox.GetPositionFromCharIndex(0).Y % (_richTextBox.Font.Height + 1);
            _numberLabel.Location = new Point(0, d);

            updateNumberLabel();
        }

        private void richTextBox1_Resize(object sender, EventArgs e) {
            richTextBox1_VScroll(null, null);
        }

        private void richTextBox1_FontChanged(object sender, EventArgs e) {
            updateNumberLabel();
            richTextBox1_VScroll(null, null);
        }




    }
}